<template>
	<view style="width:100%;">
		<nav-bar :title="title?title:''" style="width:100%;"></nav-bar>

		<block v-for="chapter in chapterList" :key="chapter.url">
			<view class="content" @click="show = !show">
				<uni-title :title="chapter.title" type="h3" class="title"></uni-title>
				<text class="txt">{{chapter.content}}</text>
			</view>
		</block>


		<u-loading-icon :show="state==-2&&!isPrevious" text="加载中"></u-loading-icon>

		<u-popup :show="show" @close="close" @open="open" round="10">
			<view class="panel">
				<view style="width: 80%;text-align: center;margin-bottom: 20px;"><text
						class="panel-title">{{title}}</text></view>
				<icon-list @select="select" :list="listIcon"></icon-list>
			</view>
		</u-popup>


		<u-popup :show="sectionsShowable" @close="closeSections" @open="initSections" closeable round="10">
			<view style="display: flex;flex-direction: column;align-items: center;">
				<view style="width: 80%;text-align: center;margin: 10px 0;"><text class="panel-title">列表</text></view>
				<scroll-view scroll-y="true" style="height:400px;" :refresher-enabled="true"
					:refresher-triggered="freshing" @refresherrefresh="">
					<uni-collapse @change="sectionChange">
						<block v-for="(section,index) in sections" :key="section.title">
							<uni-collapse-item :title="section.title" :name="index">
								<uni-list v-if="section.show">
									<uni-list-item v-for="($chapter,i) in section.list" :key="i" :title="$chapter.title"
										clickable @click="toChapter($chapter.url)">
									</uni-list-item>
								</uni-list>
							</uni-collapse-item>
						</block>
					</uni-collapse>
				</scroll-view>
			</view>

		</u-popup>


	</view>
</template>

<script>
	import utils from "@/static/js/utils.js"

	export default {
		data() {
			return {
				chapterList: [],
				bookId: -1,
				contentsId: -1,
				webId: -1,
				title: null,
				uri: '',
				isPrevious: true,
				state: -3,

				// 操作面板
				show: false,
				listIcon: [{
					icon: "left",
					text: "上一章",
					id: "previous"
				}, {
					icon: "list",
					text: "列表",
					id: "list"
				}, {
					icon: "right",
					text: "下一章",
					id: "next"
				}],

				// 章节列表弹出框
				sectionsShowable: false,
				sections: [],
				freshing: false
			}
		},
		methods: {

			toChapter(uri) {
				this.uri = uri
				uni.pageScrollTo({
					scrollTop: 0
				})
				// this.chapterList=[]
				// this.isPrevious = true
				uni.startPullDownRefresh()

			},

			sectionChange(e) {
				if (e && e.length > 0) {
					for (let i = 0; i < e.length; i++) {
						this.openItem(parseInt(e[i]))
					}
				}
			},

			openItem(index) {
				console.log("itemClick")
				if (this.sections[index].show === false) {
					this.sections[index].show = true
				}
			},

			closeSections() {
				this.sectionsShowable = false

				// setTimeout(() => {
				// 	this.show = true
				// }, 300)
			},

			initSections() {
				console.log("init sections")
				utils.http.get(`/contents/vo/${this.bookId}/${this.webId}`).then(res => {
					if (res.status == 200) {
						this.sections = this.parseChapters(res.data)
					}
				}).catch(e => {

				})
			},

			// 解析章节列表为段落列表,降低渲染代价
			parseChapters(chapters) {
				if (!chapters) {
					return []
				}
				// 段落列表
				let sections = []
				let section = null
				for (let i = 0; i < chapters.length; i = i + 20) {

					section = {
						title: `第 ${i+1}-${i+20} 章`,
						list: chapters.slice(i, i + 20),
						show: false
					}

					sections.push(section)

				}

				console.log("sections", sections)

				return sections
			},

			select(id) {
				if (id == "previous") {
					let url = this.chapterList[this.chapterList.length - 1].previousUrl
					if (!url || url == "") {
						uni.showToast({
							title: "没有上一章",
							icon: "none"
						})
						return
					}
					this.uri = url

					uni.pageScrollTo({
						scrollTop: 0
					})
					// this.chapterList=[]
					// this.isPrevious = true
					uni.startPullDownRefresh()
				} else if (id == "next") {
					let url = this.chapterList[this.chapterList.length - 1].nextUrl
					if (!url || url == "") {
						uni.showToast({
							title: "已是最新章节",
							icon: "none",
							position: "bottom"
						})
						return
					}
					this.uri = url
					uni.pageScrollTo({
						scrollTop: 0
					})
					// this.chapterList=[]
					// this.isPrevious = true
					uni.startPullDownRefresh()
				} else if (id == "list") {
					this.show = false

					setTimeout(() => {
						this.sectionsShowable = true
						this.initSections()
					}, 300)

				}
			},

			close() {
				this.show = false
			},

			open() {
				console.log("open")
			},

			toLeft() {
				uni.navigateBack()
			},

			toHome() {
				uni.switchTab({
					url: "/pages/index/index"
				})
			},

			reachBottom() {
				let url = this.chapterList[this.chapterList.length - 1].nextUrl
				if (!url || url == "") {
					uni.showToast({
						title: "已是最新章节",
						icon: "none",
						position: "bottom"
					});
					return;
				}

				this.chapter(url, false)
			},

			chapter(url, isPrevious = true) {

				if (this.state == -2) {
					return
				}

				this.isPrevious = isPrevious

				this.state = -2

				let that = this
				utils.http.get(
					`/chapter/vo?url=${url}&contentsId=${this.contentsId}&webId=${this.webId}&bookId=${this.bookId}`,
				).then(res => {
					this.state = 0

					if (res.status == 200 && res.data) {

						if (!res.data.title) {
							uni.showToast({
								title: "没有了",
								icon: "none"
							});
							return;
						}

						this.title = res.data.title


						if (isPrevious) {
							this.chapterList = []
						}

						// 处理获取的content，因为api5不支持富文本 <rich-text>标签，所以要将content处理为text
						res.data.content = res.data.content.replace(/<[^<>]+?>/g, '').replace(
							/&(lt|gt|nbsp|amp|quot);/ig,
							function(all, t) {
								let arrEntities = {
									'lt': '<',
									'gt': '>',
									'nbsp': ' ',
									'amp': '&',
									'quot': '"'
								};
								return arrEntities[t];
							});

						// 是否为上一章
						if (isPrevious) {

							this.chapterList = []
							this.chapterList.push(res.data)

							this.uri = res.data.previousUrl

						} else {
							this.chapterList.push(res.data)

						}


					}
				}).catch(e => {
					this.state = -1
				}).finally(() => {
					if (isPrevious)
						uni.stopPullDownRefresh()
				})
			}
		},

		onLoad(options) {
			this.webId = options.webId
			this.bookId = options.bookId
			this.contentsId = options.contentsId
			this.uri = options.url
			this.isPrevious = true
			uni.startPullDownRefresh()

		},

		onPullDownRefresh() {
			console.log("onPullDownRefresh")
			this.chapter(this.uri, true)
		},

		onReachBottom() {
			console.log("onReachBottom")
			this.reachBottom()
		}

	}
</script>

<style scoped>
	.content {
		background-color: #fafafa;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.title {
		text-align: center;
		line-height: 30px;
		font-size: 20px;
	}

	.txt {
		line-height: 30px;
		width: 90%;
		font-size: 18px;
		word-break: break-all;
	}


	.nav {
		width: 100%;
		background-color: white;
	}

	.nav-bar {
		width: 90%;
	}

	.panel {
		height: 200px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.panel-title {
		word-break: break-all;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		lines: 1;
		max-lines: 1;
		-webkit-line-clamp: 1;
	}
</style>
